import { useTranslate } from '@/hooks/common-hooks';
import { useNextFetchKnowledgeList } from '@/hooks/knowledge-hooks';
import {
  useAddUser,
  useDeleteUser,
  useFetchUsers,
  useUpdateUser,
} from '@/hooks/user-setting-hooks';
import { rsaPsw } from '@/utils';
import authorizationUtil from '@/utils/authorization-util';
import {
  Button,
  Card,
  Checkbox,
  Form,
  Input,
  Modal,
  Select,
  Table,
  message,
} from 'antd';
import { useState } from 'react';
import styles from './index.less';

const { Option } = Select;

const UserSettingTeam = () => {
  const { data: users, loading: usersLoading } = useFetchUsers(); // 使用 useFetchUsers 获取用户列表
  const { loading: knowledgeLoading, list: knowledgeBases } =
    useNextFetchKnowledgeList(); // 获取知识库列表
  const { t } = useTranslate('setting');
  const { addUser, isPending: addLoading } = useAddUser();
  const { updateUser, isPending: updateLoading } = useUpdateUser();
  const { deleteUser, isPending: deleteLoading } = useDeleteUser();

  const [editingUser, setEditingUser] = useState<any>(null);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [resetPassword, setResetPassword] = useState<boolean>(false); // 增加重置密码的状态
  const [form] = Form.useForm();
  const role = authorizationUtil.getRole();
  // 映射角色值到显示文本
  const roleOptions: Record<string, string> = {
    ...(role === 'owner' ? { admin: t('admin') } : {}),
    normal: t('normal'),
  };

  // 处理角色选项
  const getRoleOptions = () => {
    return Object.entries(roleOptions).map(([value, label]) => (
      <Option key={value} value={value}>
        {label}
      </Option>
    ));
  };

  const handleAddUser = () => {
    setEditingUser(null);
    setIsModalVisible(true);
  };

  const handleEditUser = (user: any) => {
    setEditingUser(user);
    setIsModalVisible(true);
    form.setFieldsValue({
      ...user,
      knowledge_details: user.knowledge_details?.map((kd: any) => kd.id), // 设置知识库的默认选项
      role: user.role || 'normal', // 设置默认角色为 normal
    });
    setResetPassword(false); // 初始化重置密码的状态
  };

  const handleDeleteUser = async (userId: any) => {
    try {
      await deleteUser(userId);
      message.success(t('delete_success'));
    } catch (error) {
      message.error(t('delete_failed'));
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();

      // 如果选择重置密码，使用当前用户的 email 作为新密码
      if (resetPassword && editingUser) {
        values.password = rsaPsw(editingUser.email);
      } else if (!editingUser) {
        // 添加用户时，设置默认密码为邮箱
        values.password = rsaPsw(values.email);
      }

      // 如果是更新用户，只传递表单中的字段
      if (editingUser) {
        await updateUser({
          user_id: editingUser.id, // 保留ID用于识别用户
          ...values, // 只传递需要更新的字段
        });
        message.success(t('update_success'));
      } else {
        await addUser(values);
        message.success(t('add_success'));
      }

      setIsModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error(t('operation_failed'));
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const columns = [
    {
      title: t('nickname'),
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: t('email'),
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: t('role'),
      dataIndex: 'role',
      key: 'role',
      render: (role: string) => roleOptions[role] || role, // 显示对应的角色名称
    },
    {
      title: t('is_active'),
      dataIndex: 'access_token',
      key: 'access_token',
      render: (accessToken: string) =>
        accessToken ? t('online') : t('offline'),
    },
    {
      title: t('knowledge_base'),
      dataIndex: 'knowledge_details',
      key: 'knowledge_details',
      render: (knowledgeDetails: any[]) =>
        knowledgeDetails && knowledgeDetails.length > 0
          ? knowledgeDetails.map((kd) => kd.name).join(' ; ')
          : t('no_knowledge_base_added'),
    },
    {
      title: t('action'),
      key: 'action',
      render: (_: any, user: any) => (
        <span>
          <Button type="link" onClick={() => handleEditUser(user)}>
            {t('edit')}
          </Button>
          <Button type="link" danger onClick={() => handleDeleteUser(user.id)}>
            {t('delete')}
          </Button>
        </span>
      ),
    },
  ];

  return (
    <div className={styles.teamWrapper}>
      <Card className={styles.teamCard}>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <span>{t('workspace')}</span>
          <Button type="primary" onClick={handleAddUser}>
            {t('add_user')}
          </Button>
        </div>
        <Table
          dataSource={users}
          columns={columns}
          rowKey="id"
          loading={
            usersLoading ||
            knowledgeLoading ||
            addLoading ||
            updateLoading ||
            deleteLoading
          } // 添加加载状态
          style={{ marginTop: '16px' }}
        />
      </Card>

      <Modal
        title={editingUser ? t('edit_user') : t('add_user')}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="nickname"
            label={t('nickname')}
            rules={[{ required: true, message: t('nickname_required') }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label={t('email')}
            rules={[{ required: true, message: t('email_required') }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="role"
            label={t('role')}
            rules={[{ required: true, message: t('role_required') }]}
          >
            <Select placeholder={t('select_role')}>{getRoleOptions()}</Select>
          </Form.Item>
          <Form.Item
            name="knowledge_details"
            label={t('knowledge_base')}
            rules={[{ required: true, message: t('knowledge_base_required') }]}
          >
            <Select mode="multiple" placeholder={t('select_knowledge_base')}>
              {knowledgeBases.map((kb: any) => (
                <Option key={kb.id} value={kb.id}>
                  {kb.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          {editingUser && (
            <Form.Item name="reset_password" valuePropName="checked">
              <Checkbox onChange={(e) => setResetPassword(e.target.checked)}>
                {t('reset_password')}
              </Checkbox>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default UserSettingTeam;
